package com.cccccc.service;

import com.cccccc.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * --- 代码敲对！ ---
 *
 * @author CCCccc
 * @create 2025/8/22
 * 备注：
 * UserDerailsServiceUmpl类实现了UserDetailsService接口，用于加载用户信息。
 */
@Service
public class UserDerailsServiceUmpl implements UserDetailsService{
    @Autowired
    private UserMapper userMapper; // 注入UserMapper


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.cccccc.object.User user = userMapper.selectUserByUsername(username); // 根据用户名查询用户信息
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在"); // 如果用户不存在，抛出异常
        }

        Set<String> authSet = userMapper.selectById(user.getId()); // 根据用户名查询用户权限
        System.out.println("authSet = " + authSet);
        System.out.println("user = " + user);

        Set<GrantedAuthority> auths = new HashSet<>(); // 创建权限集合
        for (String auth : authSet) {
            auths.add(new SimpleGrantedAuthority(auth)); // 将权限添加到集合中
        }
        String role = userMapper.selectRoleById(user.getId()); // 根据用户id查询用户角色
        if (role != null) {
            auths.add(new SimpleGrantedAuthority("ROLE_"+role)); // 如果用户有角色，将角色添加到权限集合中
        }else {
            auths.add(new SimpleGrantedAuthority("ROLE_User")); // 如果用户没有角色，将默认角色添加到权限集合中
        }
        return new User(user.getUsername(), user.getPassword(), auths); // 返回用户信息
    }
}
